/***********************************************************
 * @Description : 用户服务
 * @author      : 梁山广(Laing Shan Guang)
 * @date        : 2019-05-17 08:03
 * @email       : liangshanguang2@gmail.com
 ***********************************************************/
package lsgwr.exam.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import lsgwr.exam.dto.RegisterDTO;
import lsgwr.exam.entity.*;
import lsgwr.exam.enums.LoginTypeEnum;
import lsgwr.exam.enums.RoleEnum;
import lsgwr.exam.qo.LoginQo;
import lsgwr.exam.repository.*;
import lsgwr.exam.service.SysUserService;
import lsgwr.exam.service.UserService;
import lsgwr.exam.utils.JwtUtils;
import lsgwr.exam.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    UserRepository userRepository;

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    PageRepository pageRepository;

    @Autowired
    ActionRepository actionRepository;

    @Autowired
    ExamRecordRepository examRecordRepository;


    @Override
    public List<UserVo> getUserList() {
        List<User> userList = userRepository.findAll();
        List<UserVo> userVoList = new ArrayList<>();
        for (User user : userList) {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            userVoList.add(userVo);
        }
        return userVoList;
    }

    @Override
    public UserVo getInfo(String id) {
        User user = userRepository.findById(id).orElse(null);
        assert user != null;
        UserVo userVo = new UserVo();
        // 1.尽可能的拷贝属性
        BeanUtils.copyProperties(user, userVo);
        return userVo;
    }

    @Override
    public void saveUser(User user) {
        userRepository.save(user);
    }

    @Override
    public void updateUser(UserVo userVo) {
       User oldUser = userRepository.findById(userVo.getUserId()).orElse(null);
       if(userVo.getUserEmail() != null){
           oldUser.setUserEmail(userVo.getUserEmail());
       }
       if(userVo.getUserPhone() != null){
           oldUser.setUserPhone(userVo.getUserPhone());
       }
       oldUser.setUserNickname(userVo.getUserUsername());
       oldUser.setUserUsername(userVo.getUserUsername());
       oldUser.setUserRoleId(userVo.getUserRoleId());
       userRepository.save(oldUser);
    }

    @Override
    public void deleteUser(String id) {
        userRepository.deleteById(id);
        List<ExamRecord> examRecords = examRecordRepository.findByExamJoinerIdOrderByExamJoinDateDesc(id);
        for(ExamRecord examRecord : examRecords){
            examRecordRepository.delete(examRecord);
        }
    }
}
